package site.anxuan.seckill.listener;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import site.anxuan.seckill.service.ItemService;

@Component
@AllArgsConstructor
@RocketMQMessageListener(topic = "seckill", consumerGroup = "seckill_sales",
        selectorExpression = "increase_sales")
public class IncreaseSalesListener implements RocketMQListener<String> {

    private final Logger logger = LoggerFactory.getLogger(IncreaseSalesListener.class);

    private final ItemService itemService;

    @Override
    public void onMessage(String s) {
        JSONObject jsonObject = JSONObject.parseObject(s);
        int itemId = (int) jsonObject.get("itemId");
        int amount = (int) jsonObject.get("amount");
        try {
            itemService.increaseSales(itemId, amount);
        } catch (Exception e) {
            logger.error("商品["+ itemId +"]增加" + amount + "个销量失败，等待稍后重试.");
        }
    }

}
